import { useState, useEffect } from "react";
import { useNavigate, Outlet, useLocation } from "react-router-dom";
import {
  Layout,
  Menu,
  Input,
  List,
  Card,
  Avatar,
  Tag,
  Button,
  Spin,
  Dropdown,
  Modal,
  Tabs,
  Badge,
  message,
  Progress,
  Alert,
  Tooltip,
} from "antd";
const { Header, Content, Sider } = Layout;
const { TabPane } = Tabs;
import {
  UserOutlined,
  SearchOutlined,
  FireOutlined,
  UploadOutlined,
  ClockCircleOutlined,
  BarChartOutlined,
  DownloadOutlined,
  FileTextOutlined,
  DatabaseOutlined,
  CalendarOutlined,
  RightOutlined,
  LeftOutlined,
  CrownOutlined,
  TrophyOutlined,
  HomeOutlined,
  InfoCircleOutlined,
  SecurityScanOutlined,
  UserSwitchOutlined,
  FlagOutlined,
  ThunderboltOutlined,
  BellOutlined, StarOutlined, HeartOutlined,
} from "@ant-design/icons";
import TorrentUpload from "@/pages/home/TorrentUpload";
import { generateMockTorrents, mockUser } from "@mock";
import "./home.styl";
import axios from "axios";
import { getAuthToken } from "@/router/index.jsx";
import { ClockIcon } from "@heroicons/react/24/outline";
import {
  activeResourceFreeDownload,
  checkDoubleUploadStatus,
  loadUnreadNotificationsApi,
  markNotificationReadedApi, setFreeDownloadApi,
} from "@/api/index.jsx";

const CategoryIcon = ({ category }) => {
  const icons = {
    movie: <FileTextOutlined />,
    music: <FileTextOutlined />,
    game: <FileTextOutlined />,
    software: <FileTextOutlined />,
  };
  return icons[category] || <FileTextOutlined />;
};
const TorrentItem = ({ item, isAdmin, navigate}) => (
    <List.Item
        className="torrent-item"
        actions={[
          <div key="stats" className="meta-stats">
        <span className="stat">
          <ClockCircleOutlined /> {item.seederCount || item.seeders} 做种
        </span>
            <span className="stat">
          <DownloadOutlined /> {item.downloadCount || item.downloads} 下载
        </span>
            {item.recommendationLevel && (
                <span className="stat">
            <StarOutlined /> 推荐等级: {item.recommendationLevel}
          </span>
            )}
            {isAdmin && (
                <Button
                    type="dashed"
                    size="small"
                    icon={
                      <ClockIcon
                          style={{
                            width: 18,
                            height: 18,
                            color: "#06b6d4",
                            marginRight: 2,
                          }}
                      />
                    }
                    style={{
                      marginLeft: 8,
                      color: "#06b6d4",
                      borderColor: "#06b6d4",
                      fontWeight: 500,
                    }}
                    onClick={() => handleActiveFreeDownload(item.id)}
                >
                  限时免费
                </Button>
            )}
          </div>,
          <Tag
              key="category"
              icon={<CategoryIcon category={item.category} />}
              color="geekblue"
              className="category-tag"
          >
            {item.category}
          </Tag>,
        ]}
    >
      <List.Item.Meta
          avatar={
            <div className="torrent-cover">
              {item.cover ? (
                  <img src={item.cover} alt={item.name} />
              ) : (
                  <FileTextOutlined
                      style={{ fontSize: 40, color: "#1890ff" }}
                  />
              )}
            </div>
          }
          title={
            <Button
                type="link"
                onClick={() => navigate(`/torrent/${item.id}`)}
                className="torrent-title"
            >
              {item.name}
            </Button>
          }
          description={
            <div className="torrent-description">
              <div className="size-info">
                <DatabaseOutlined /> {formatBytes (item.size)}
                <span className="upload-time">
              <CalendarOutlined />{" "}
                  {new Date(item.createdAt).toLocaleDateString()}
            </span>
              </div>
              {item.description && (
                  <div className="excerpt">
                    {item.description}
                  </div>
              )}
            </div>
          }
      />
      <Button
          type="primary"
          size="small"
          onClick={() => navigate(`/torrent/${item.id}`)}
          className="detail-btn"
      >
        查看详情 <RightOutlined />
      </Button>
    </List.Item>
);
const handleActiveFreeDownload = (torrentId) => {
  setFreeDownloadApi({
    torrentId: torrentId,
    freeHours: 24, // 设置免费小时数，这里设为24小时
    reason: "管理员手动设置限时免费" // 设置原因
  }).then(res => {
    if (res.code === 200) {
      message.success(`资源 #${torrentId} 已设置为限时免费下载`);
    } else {
      message.error(res.msg || "设置限时免费失败");
    }
  }).catch(error => {
    console.error("设置限时免费失败:", error);
    message.error("设置限时免费失败，请稍后重试");
  });
};

const formatBytes = (bytes) => {
  if (!bytes) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};
const Home = () => {
  const [torrents, setTorrents] = useState([]);
  const [hotList, setHotList] = useState([]);
  const [userData, setUserData] = useState({
    username: "加载中...",
    ratio: 0,
    uploaded: "0 B",
    downloaded: "0 B",
    avatar: null,
  });
  const [loading, setLoading] = useState(true);
  const [openKeys, setOpenKeys] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [searchResults, setSearchResults] = useState(null);
  const [leaderboardData, setLeaderboardData] = useState({
    upload: [],
    seeding: [],
  });
  const [rankingLoading, setRankingLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false); // 新增：管理员状态
  const [adminChecking, setAdminChecking] = useState(false); // 新增：管理员检查中状态
  const navigate = useNavigate();
  const location = useLocation();
  // 标记当前是否处于双倍上传奖励时段(开发阶段未调试接口，暂定处于双倍期间)
  const [isDoubleUpload, setIsDoubleUpload] = useState(true);

  // 状态管理分享率
  const [ratioStatus, setRatioStatus] = useState(null);
  const [ratioModalVisible, setRatioModalVisible] = useState(false);
  const [ratioLoading, setRatioLoading] = useState(false);

  // 消息通知相关
  const [notifications, setNotifications] = useState([]);

  const [notifDropdownOpen, setNotifDropdownOpen] = useState(false);

  // 未读消息数量
  const unreadCount = notifications.filter((n) => !n.isRead).length;

  // 标记已读
  const handleMarkRead = (id) => {
    console.log('${id}'+ 'id')
    axios
        .post(
            `http://192.168.55.192:8080/api/user/notifications/${id}/read`,
            null,
            {
              headers: { Authorization: getAuthToken() },
            }
        )
        .then((response) => {
          if (response.data.code === 200) {
            // 刷新消息列表
            loadUnreadNotifications();
          } else {
            message.error(response.data.msg || "标记已读失败");
          }
        })
        .catch((error) => {
          console.error("标记已读失败:", error);
          message.error("标记已读失败");
        });
  };



  // 获取用户分享率状态
  const fetchShareRatioStatus = async () => {
    setRatioLoading(true);
    try {
      // 模拟API调用
      setTimeout(() => {
        const ratio = userData.ratio;
        let statusData;

        if (ratio >= 1.0) {
          statusData = {
            status: "normal",
            restriction: null,
            message: "您的分享率健康！继续保持上传吧！",
            progress: {
              value: Math.min(100, Math.round(ratio * 20)),
              status: "success",
            },
          };
        } else if (ratio >= 0.5) {
          statusData = {
            status: "warning",
            restriction: null,
            message: "您的分享率较低，请上传更多资源",
            progress: {
              value: Math.min(100, Math.round(ratio * 100)),
              status: "normal",
            },
          };
        } else {
          statusData = {
            status: "restricted",
            restriction: {
              can_download: false,
              message: "分享率低于0.5，禁止下载新种子",
            },
            message: "您的分享率过低，账户功能已受限",
            progress: {
              value: Math.min(100, Math.round(ratio * 100)),
              status: "exception",
            },
          };
        }

        setRatioStatus({
          share_ratio: ratio,
          ...statusData,
        });
        setRatioLoading(false);
      }, 500);
    } catch (error) {
      console.error("获取分享率状态失败:", error);
      message.error("无法获取分享率状态");
      setRatioStatus(null);
      setRatioLoading(false);
    }
  };

  // 检查管理员权限
  const checkAdminPermission = async () => {
    setAdminChecking(true);
    try {
      // 暂时注释掉，默认为管理员
      // const response = await axios.get('http://192.168.55.192:8080/api/admin/check', {
      //   headers: { Authorization: getAuthToken() }
      // });

      // if (response.data.code === 200 && response.data.data.isAdmin) {
      //   setIsAdmin(true);
      // } else {
      //   setIsAdmin(false);
      // }
      console.log(11111111);
      setIsAdmin(true);
    } catch (error) {
      console.error("检查管理员权限失败:", error);
      // 在生产环境中，应该完全依赖于API响应
      // 这里为了演示目的，如果API出错，使用mockUser中的值
      setIsAdmin(mockUser.isAdmin || false);
    } finally {
      setAdminChecking(false);
    }
  };

  // 获取排行榜数据
  const fetchLeaderboard = async () => {
    try {
      const [uploadRes, seedingRes] = await Promise.all([
        axios.get("http://192.168.55.192:8080/api/leaderboard/upload", {
          headers: { Authorization: getAuthToken() },
        }),
        axios.get("http://192.168.55.192:8080/api/leaderboard/seeding", {
          headers: { Authorization: getAuthToken() },
        }),
      ]);

      const uploadData = uploadRes.data.code === 200
          ? uploadRes.data.data.map(item => ({
            ...item,
            scoreDisplay: formatBytes(item.score) // 将字节转换为易读格式
          }))
          : mockRankings.upload;

      // 处理保种榜数据
      const seedingData = seedingRes.data.code === 200
          ? seedingRes.data.data.map(item => ({
            ...item,
            scoreDisplay: `${(item.score / 3600).toFixed(1)}小时` // 秒转小时
          }))
          : mockRankings.seeding;

      setLeaderboardData({
        upload: uploadData,
        seeding: seedingData,
      });
    } catch (error) {
      console.error("排行榜加载失败，使用虚拟数据:", error);
      setLeaderboardData(mockRankings);
    } finally {
      setRankingLoading(false);
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        console.log(`${getAuthToken()}`)
        const [hotResponse, userInfoResponse, mockData] = await Promise.all([
          axios.get("http://192.168.55.192:8080/api/torrent/list", {
            headers: { Authorization: `${getAuthToken()}` },
          }),
          axios.get("http://192.168.55.192:8080/api/user/info", {
            headers: { Authorization: `${getAuthToken()}` },
          }),
          JSON.parse(localStorage.getItem("mockTorrents")) || generateMockTorrents(),
        ]);
        const backendHotList =
          hotResponse.data.code === 200 ? hotResponse.data.data.records : [];

        setHotList(backendHotList.slice(0, 5));

        const processedMockData = mockData.map((item) => ({
          ...item,
          cover:
            Math.random() > 0.5 ? `https://picsum.photos/80?${item.id}` : null,
          description:
            Math.random() > 0.3
              ? `这是一个关于${item.category}的高质量资源...`
              : null,
        }));
        localStorage.setItem("mockTorrents", JSON.stringify(processedMockData));
        setTorrents(processedMockData.slice(0, 10));

        if (userInfoResponse.data.code === 200) {
          const userInfo = userInfoResponse.data.data;
          setUserData({
            username: userInfo.username,
            ratio: userInfo.shareRatio,
            uploaded: formatBytes(userInfo.uploadAmount),
            downloaded: formatBytes(userInfo.downloadAmount),
            avatar: null, // API未提供头像，保持为null
            // 添加其他可能需要的数据字段
            userLevel: userInfo.userLevel,
            magicValue: userInfo.magicValue,
          });
        } else {
          // API失败时使用mock数据作为后备
          console.warn("用户信息获取失败，使用mock数据");
          setUserData({
            username: mockUser.username,
            ratio: mockUser.ratio,
            uploaded: formatBytes(mockUser.uploaded),
            downloaded: formatBytes(mockUser.downloaded),
            avatar: mockUser.avatar,
          });
        }
      } catch (error) {
        console.warn("数据加载异常:", error);
        const mockData =
            JSON.parse(localStorage.getItem("mockTorrents")) ||
            generateMockTorrents();
        setHotList([...mockData].sort(() => Math.random() - 0.5).slice(0, 5));
      } finally {
        setLoading(false);
      }
    };

    const init = async () => {
      await Promise.all([
        fetchData(),
        fetchLeaderboard(),
        checkAdminPermission(), // 新增：获取管理员权限
      ]);
    };

    setTimeout(init, 1000);
  }, []);

  const handleMenuOpenChange = (keys) => {
    setOpenKeys(keys.length ? [keys[keys.length - 1]] : []);
  };

  const handleLogout = async () => {
    try {
      await axios.post("http://192.168.55.192:8080/api/auth/logout", null, {
        headers: { Authorization: getAuthToken() },
      });
      message.success("已安全退出");
    } catch (error) {
      message.error("退出登录失败");
      console.error("登出失败:", error);
    } finally {
      localStorage.removeItem("token");
      navigate("/login", { replace: true });
    }
  };

  // 点击查看状态时触发
  const handleCheckRatio = async () => {
    if (!ratioStatus) {
      await fetchShareRatioStatus();
    }
    setRatioModalVisible(true);
  };

  // 构建菜单项，根据管理员状态添加额外选项
  const getMenuItems = () => {
    const items = [
      { key: "/", label: "首页", icon: <HomeOutlined /> },
      { key: "/recommend", label: "种子推荐", icon: <StarOutlined /> },
      { key: "/community/bounty", label: "资源悬赏", icon: <FlagOutlined /> },
      {
        key: "user",
        label: "个人中心",
        icon: <UserOutlined />,
        children: [
          { key: "/user/profile", label: "个人信息" },
          { key: "/user/security", label: "安全设置" },
          { key: "/user/magic", label: "魔力明细" },
          { key: "/user/invites", label: "邀请管理" },
          { key: "/user/torrent-history", label: "种子记录" },
          { key: "/user/marathons", label: "保种马拉松" },
          { key: "/user/discount-coupons", label: "下载折扣券" },
        ],
      },
    ];

    // 如果是管理员，添加管理员菜单
    if (isAdmin) {
      items.push(
        {
          key: "admin-torrent",
          label: "种子管理",
          icon: <SecurityScanOutlined />,
          children: [{ key: "/admin/torrent/pending", label: "待审核种子" }],
        },
        {
          key: "admin-user",
          label: "用户管理",
          icon: <UserSwitchOutlined />,
          children: [
            { key: "/admin/user/list", label: "封禁管理" },
            { key: "/admin/user/operation-logs", label: "操作日志" },
          ],
        },
      {
        key: "admin-activity",
            label: "活动管理",
          icon: <CrownOutlined />,
          children: [{ key: "/admin/activities", label: "活动管理" }],
      }
      );
    }

    return items;
  };

  const userMenu = (
    <Menu
      items={[
        {
          key: "profile",
          label: "个人资料",
          onClick: () => navigate("/user/profile"),
        },
        { key: "logout", label: "退出登录", onClick: handleLogout },
      ]}
    />
  );

  const handleSearch = async (value) => {
    try {
      setLoading(true);
      const response = await axios.get(
        `http://192.168.55.192:8080/api/torrent/search`,
        {
          params: { keyword: value },
          headers: { Authorization: `${getAuthToken()}` },
        }
      );

      const results =
        response.data.code === 200 ? response.data.data.records : [];
      setSearchResults(results);
    } catch (error) {
      console.error("搜索请求失败:", error);
      setSearchResults([]);
    } finally {
      setLoading(false);
    }
  };

  const handleBackToHot = () => {
    setSearchResults(null);
  };

  // 处理开放资源免费下载

  const loadUnreadNotifications = () => {
    axios
        .get("http://192.168.55.192:8080/api/user/notifications/unread", {
          headers: { Authorization: getAuthToken() },
        })
        .then((response) => {
          if (response.data && response.data.code === 200 && Array.isArray(response.data.data)) {
            const formattedNotifications = response.data.data.map((item) => ({
              id: item.id,
              title: item.title,
              content: item.content,
              notifyType: item.notifyType,
              isRead: item.readAt ? 1 : 0,
              createdAt: item.createdAt,
              readAt: item.readAt
            }));
            setNotifications(formattedNotifications);
          } else {
            message.error(response.data?.msg || "获取通知失败");
          }
        })
        .catch((error) => {
          console.error("加载通知失败:", error);
          message.error("加载通知失败");
        });
  };

  // 检测当前是否处于双倍上传积分时段，加载当前用户消息通知
  useEffect(() => {
    checkDoubleUploadStatus().then((res) => {
      // 如果当前处于双倍上传奖励时段，则设置isDoubleUpload为true
      console.log(res);
      // setIsDoubleUpload(res.data.code === 200);
    });
    loadUnreadNotifications();
  }, []);

  return (
    <Layout className="home-layout">
      {isAdmin}
      <Header className="header">
        <div className="logo" onClick={() => navigate("/")}>
          PT Tracker
        </div>
        <Input.Search
          placeholder="搜索资源..."
          enterButton={<SearchOutlined />}
          className="search-bar"
          onSearch={handleSearch}
        />

        {/* 用户消息通知 */}
        <div className="user-actions">
          <Dropdown
            overlayStyle={{ width: 300 }}
            menu={{
              items:
                notifications.length === 0
                  ? [
                      {
                        key: "empty",
                        label: <div className="notif-empty">暂无消息</div>,
                        disabled: true,
                      },
                    ]
                  : notifications.map((msg) => ({
                      key: msg.id,
                      label: (
                        <div
                          className={`notif-item${msg.isRead ? " read" : ""}`}
                          onClick={(e) => e.stopPropagation()}
                        >
                          <div className="notif-title">{msg.title}</div>
                          <div className="notif-content">{msg.content}</div>
                          <div
                            className="notif-meta"
                            style={{ display: "flex" }}
                          >
                            <span className="notif-date">
                              {new Date(msg.createdAt).toLocaleString()}
                            </span>
                            {!msg.isRead && <span style={{ flex: 1 }} />}
                            {!msg.isRead && (
                              <Button
                                type="link"
                                size="small"
                                style={{ marginLeft: "auto", paddingRight: 0 }}
                                onClick={() => {
                                  handleMarkRead(msg.id);
                                  setNotifDropdownOpen(true);
                                }}
                              >
                                已读
                              </Button>
                            )}
                          </div>
                        </div>
                      ),
                    })),
            }}
            trigger={["click"]}
            placement="bottomRight"
            overlayClassName="notif-dropdown-menu"
            open={notifDropdownOpen}
            onOpenChange={setNotifDropdownOpen}
          >
            <div className="notif-bell-wrapper">
              <Badge count={unreadCount} size="small" offset={[-2, 2]}>
                <BellOutlined className="notif-bell" />
              </Badge>
            </div>
          </Dropdown>
          <Dropdown overlay={userMenu} trigger={["click"]}>
            <div className="user-info">
              <Avatar icon={<UserOutlined />} src={userData.avatar} />
              <span className="username">{userData.username}</span>
              {/* 显示管理员徽章 */}
              {isAdmin && (
                <Badge.Ribbon
                  text="管理员"
                  color="volcano"
                  className="admin-badge"
                  placement="end"
                />
              )}
            </div>
          </Dropdown>
        </div>
      </Header>

      {loading || adminChecking ? (
        <div className="loading-container">
          <Spin size="large" tip="数据加载中..." />
        </div>
      ) : (
        <Layout>
          <Sider width={260} theme="light" className="left-sider">
            <Menu
              mode="inline"
              items={getMenuItems()}
              selectedKeys={[location.pathname]}
              openKeys={openKeys}
              onOpenChange={handleMenuOpenChange}
              onSelect={({ key }) => navigate(key)}
              style={{ borderRight: 0 }}
            />

            <Card
              className="user-stats"
              title="数据统计"
              bordered={false}
              extra={
                <Button
                  type="link"
                  size="small"
                  icon={<InfoCircleOutlined />}
                  onClick={handleCheckRatio}
                >
                  查看状态
                </Button>
              }
            >
              <div className="stat-item">
                <span>上传量</span>
                <Tag color="blue">{userData.uploaded}</Tag>
              </div>
              <div className="stat-item">
                <span>下载量</span>
                <Tag color="purple">{userData.downloaded}</Tag>
              </div>
              <div className="stat-item">
                <span>分享率</span>
                <Tag color={userData.ratio >= 1 ? "green" : "red"}>
                  {userData.ratio.toFixed(2)}
                </Tag>
              </div>
            </Card>

            <Card
              className="ranking-card"
              title="实时排行榜"
              bordered={false}
              extra={
                <Button
                  type="link"
                  size="small"
                  onClick={() => navigate("/ranking")}
                  icon={<BarChartOutlined />}
                >
                  完整榜单
                </Button>
              }
            >
              <Spin spinning={rankingLoading} tip="加载排行榜...">
                <Tabs defaultActiveKey="upload" size="small" tabBarGutter={16}>
                  <TabPane
                    key="upload"
                    tab={
                      <span>
                        <UploadOutlined />
                        上传榜
                      </span>
                    }
                  >
                    <List
                      size="small"
                      dataSource={leaderboardData.upload.slice(0, 3)}
                      renderItem={(item, index) => (
                        <List.Item className="ranking-item">
                          <div className="rank-info">
                            <Badge
                              count={index + 1}
                              style={{ backgroundColor: "#1890ff" }}
                            />
                            <div className="rank-detail">
                              <div className="username">{item.username}</div>
                              <Tag>Lv.{item.userLevel}</Tag>
                            </div>
                          </div>
                          <Tag className="magic-tag">{item.scoreDisplay}</Tag>
                        </List.Item>
                      )}
                    />
                  </TabPane>
                  <TabPane
                    key="seeding"
                    tab={
                      <span>
                        <ClockCircleOutlined />
                        保种榜
                      </span>
                    }
                  >
                    <List
                      size="small"
                      dataSource={leaderboardData.seeding.slice(0, 3)}
                      renderItem={(item, index) => (
                        <List.Item className="ranking-item">
                          <div className="rank-info">
                            <Badge
                              count={index + 1}
                              style={{ backgroundColor: "#1890ff" }}
                            />
                            <div className="rank-detail">
                              <div className="username">{item.username}</div>
                              <Tag>Lv.{item.userLevel}</Tag>
                            </div>
                          </div>
                          <Tag className="magic-tag">{item.scoreDisplay}</Tag>
                        </List.Item>
                      )}
                    />
                  </TabPane>
                </Tabs>
              </Spin>
            </Card>
          </Sider>

          <Content className="main-content">
            {location.pathname === "/" && (
              <>
                <div className="upload-btn">
                  <Tooltip
                    title={
                      isDoubleUpload
                        ? "当前为双倍上传奖励时段，上传资源可获得双倍积分！"
                        : undefined
                    }
                    open={isDoubleUpload ? undefined : false}
                  >
                    <Button
                      type="primary"
                      icon={<UploadOutlined />}
                      className={isDoubleUpload ? "double-upload-btn" : ""}
                      onClick={() => setModalOpen(true)}
                    >
                      上传资源
                      {isDoubleUpload && (
                        <Tag color="gold" className="double-tag">
                          双倍上传
                        </Tag>
                      )}
                    </Button>
                  </Tooltip>
                </div>
                <div className="torrent-section">
                  {searchResults ? (
                    <>
                      <div className="search-result-header">
                        <h2>
                          <Button
                            type="link"
                            onClick={handleBackToHot}
                            icon={<LeftOutlined />}
                            style={{ marginRight: 8 }}
                          >
                            返回
                          </Button>
                          <SearchOutlined /> 搜索结果 (共{searchResults.length}
                          条)
                        </h2>
                      </div>
                      <List
                        itemLayout="vertical"
                        dataSource={searchResults}
                        renderItem={(item) => (
                          <List.Item
                            className="torrent-item"
                            actions={[
                              <div key="stats" className="meta-stats">
                                <span className="stat">
                                  <ClockCircleOutlined /> {item.seederCount}{" "}
                                  做种
                                </span>
                                <span className="stat">
                                  <DownloadOutlined /> {item.downloadCount} 下载
                                </span>
                                <span className="stat">
                                  下载中 {item.leecherCount}
                                </span>
                                <span className="stat">
                                  下载中 {item.leecherCount}
                                </span>
                              </div>,
                              <Tag
                                key="category"
                                icon={<CategoryIcon category={item.category} />}
                                color="geekblue"
                                className="category-tag"
                              >
                                {item.category}
                              </Tag>,
                            ]}
                          >
                            <List.Item.Meta
                              avatar={
                                <div className="torrent-cover">
                                  {item.cover ? (
                                    <img src={item.cover} alt={item.name} />
                                  ) : (
                                    <FileTextOutlined
                                      style={{ fontSize: 40, color: "#1890ff" }}
                                    />
                                  )}
                                </div>
                              }
                              title={
                                <Button
                                  type="link"
                                  onClick={() =>
                                    navigate(`/torrent/${item.id}`)
                                  }
                                  className="torrent-title"
                                >
                                  {item.name}
                                </Button>
                              }
                              description={
                                <div className="torrent-description">
                                  <div className="size-info">
                                    <DatabaseOutlined />{" "}
                                    {formatBytes(item.size)}
                                    <span className="upload-time">
                                      <CalendarOutlined />{" "}
                                      {new Date(
                                        item.createdAt
                                      ).toLocaleDateString()}
                                    </span>
                                  </div>
                                  {item.description && (
                                    <div className="excerpt">
                                      {item.description}
                                    </div>
                                  )}
                                </div>
                              }
                            />
                            <Button
                              type="primary"
                              size="small"
                              onClick={() => navigate(`/torrent/${item.id}`)}
                              className="detail-btn"
                            >
                              查看详情 <RightOutlined />
                            </Button>
                          </List.Item>
                        )}
                      />
                    </>
                  ) : (
                    <>
                      <h2>
                        <FireOutlined /> 热门下载
                      </h2>
                      <List
                        itemLayout="vertical"
                        dataSource={hotList}
                        renderItem={(item) => (
                          <List.Item
                            className="torrent-item"
                            actions={[
                              <div key="stats" className="meta-stats">
                                <span className="stat">
                                  <ClockCircleOutlined /> {item.seeders} 做种
                                </span>
                                <span className="stat">
                                  <DownloadOutlined /> {item.downloads} 下载
                                </span>
                                <span className="stat">
                                  {item.ratingCount > 0
                                    ? (
                                        item.ratingSum / item.ratingCount
                                      ).toFixed(1)
                                    : "无评分"}
                                </span>
                                {/* 添加限时免费-管理员用户才具备改按钮 - 还需要注意，如果当前资源已经是免费开放中，则不应该显示此按钮*/}
                                {isAdmin && (
                                  <Button
                                    type="dashed"
                                    size="small"
                                    icon={
                                      <ClockIcon
                                        style={{
                                          width: 18,
                                          height: 18,
                                          color: "#06b6d4",
                                          marginRight: 2,
                                        }}
                                      />
                                    }
                                    style={{
                                      marginLeft: 8,
                                      color: "#06b6d4",
                                      borderColor: "#06b6d4",
                                      fontWeight: 500,
                                    }}
                                    onClick={() =>
                                      handleActiveFreeDownload(item.id)
                                    }
                                  >
                                    限时免费
                                  </Button>
                                )}
                              </div>,
                              <Tag
                                key="category"
                                icon={<CategoryIcon category={item.category} />}
                                color="geekblue"
                                className="category-tag"
                              >
                                {item.category}
                              </Tag>,
                            ]}
                          >
                            <List.Item.Meta
                              avatar={
                                <div className="torrent-cover">
                                  {item.cover ? (
                                    <img src={item.cover} alt={item.name} />
                                  ) : (
                                    <FileTextOutlined
                                      style={{ fontSize: 40, color: "#1890ff" }}
                                    />
                                  )}
                                </div>
                              }
                              title={
                                <Button
                                  type="link"
                                  onClick={() =>
                                    navigate(`/torrent/${item.id}`)
                                  }
                                  className="torrent-title"
                                >
                                  {item.name}
                                </Button>
                              }
                              description={
                                <div className="torrent-description">
                                  <div className="size-info">
                                    <DatabaseOutlined />{" "}
                                    {formatBytes(item.size)}
                                    <span className="upload-time">
                                      <CalendarOutlined />{" "}
                                      {new Date(
                                        item.createdAt
                                      ).toLocaleDateString()}
                                    </span>
                                  </div>
                                  {item.description && (
                                    <div className="excerpt">
                                      {item.description}
                                    </div>
                                  )}
                                </div>
                              }
                            />
                            <Button
                              type="primary"
                              size="small"
                              onClick={() => navigate(`/torrent/${item.id}`)}
                              className="detail-btn"
                            >
                              查看详情 <RightOutlined />
                            </Button>
                          </List.Item>
                        )}
                      />
                    </>
                  )}
                </div>
              </>
            )}
            <Outlet />
          </Content>
        </Layout>
      )}

      {/* 上传资源模态框 */}
      <Modal
        title="上传种子"
        open={modalOpen}
        onCancel={() => setModalOpen(false)}
        footer={null}
        width={800}
        destroyOnClose
      >
        {isDoubleUpload && (
          <Alert
            message="双倍上传奖励中！"
            description="现在上传资源可获得双倍上传积分，快来参与吧！"
            type="success"
            showIcon
            icon={
              <ThunderboltOutlined
                style={{
                  color: "#faad14",
                }}
              />
            }
            style={{ marginBottom: 16 }}
          />
        )}
        <TorrentUpload onClose={() => setModalOpen(false)} />
      </Modal>

      {/* 分享率状态模态框 */}
      <Modal
        title="分享率状态"
        open={ratioModalVisible}
        onCancel={() => setRatioModalVisible(false)}
        footer={null}
        centered
        destroyOnClose
      >
        {ratioLoading ? (
          <div style={{ textAlign: "center", padding: "30px 0" }}>
            <Spin size="large" tip="检查分享率状态..." />
          </div>
        ) : ratioStatus ? (
          <div className="ratio-status-content">
            <Progress
              type="circle"
              percent={ratioStatus.progress.value}
              status={ratioStatus.progress.status}
              format={() => (
                <div className="ratio-value">
                  {ratioStatus.share_ratio.toFixed(2)}
                  <div className="ratio-label">分享率</div>
                </div>
              )}
              width={120}
              strokeWidth={12}
              strokeColor={{
                "0%": "#1890ff",
                "100%":
                  ratioStatus.status === "normal"
                    ? "#52c41a"
                    : ratioStatus.status === "warning"
                    ? "#faad14"
                    : "#ff4d4f",
              }}
              className="ratio-progress"
            />

            <div className="ratio-status-info">
              <Alert
                message={ratioStatus.message}
                type={
                  ratioStatus.status === "normal"
                    ? "success"
                    : ratioStatus.status === "warning"
                    ? "warning"
                    : "error"
                }
                showIcon
                className="status-alert"
              />

              {ratioStatus.status === "restricted" && (
                <div className="restriction-detail">
                  <p className="restriction-title">
                    <InfoCircleOutlined /> 账户限制
                  </p>
                  <p className="restriction-message">
                    {ratioStatus.restriction.message}
                  </p>
                  <p className="restriction-solution">
                    <strong>如何解决:</strong>{" "}
                    请上传更多资源并保持做种以提升分享率。
                    当分享率超过0.5后，限制将自动解除。
                  </p>
                </div>
              )}

              <div className="ratio-tips">
                <p>
                  <strong>分享率计算公式:</strong> 上传量 ÷ 下载量
                </p>
                <p>
                  <strong>健康值范围:</strong> 推荐保持在1.0以上
                </p>
                <p>
                  <strong>提示:</strong> 上传种子并长时间做种可快速提升分享率
                </p>
              </div>
            </div>
          </div>
        ) : (
          <Alert
            message="无法获取分享率状态"
            description="可能是网络问题或服务异常，请稍后重试"
            type="error"
            showIcon
          />
        )}
      </Modal>
    </Layout>
  );
};

export const mockRankings = {
  upload: Array.from({ length: 10 }, (_, i) => ({
    rank: i + 1,
    userId: 1000 + i,
    username: `上传达人${i + 1}`,
    userLevel: Math.floor(Math.random() * 5) + 1,
    score: 50000000 - i * 5000000,
    scoreDisplay: `${50 - i * 5}GB`,
    type: "upload",
  })),
  seeding: Array.from({ length: 10 }, (_, i) => ({
    rank: i + 1,
    userId: 2000 + i,
    username: `保种专家${i + 1}`,
    userLevel: Math.floor(Math.random() * 5) + 1,
    score: 259200 - i * 21600,
    scoreDisplay: `${3.0 - i * 0.25}天`,
    type: "seeding",
  })),
};
export const RecommendPage = () => {
  const [activeTab, setActiveTab] = useState("personalized");
  const [loading, setLoading] = useState(false);
  const [torrents, setTorrents] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const navigate = useNavigate();

  const formatBytes = (bytes) => {
    if (!bytes) return "0 B";
    const k = 1024;
    const sizes = ["B", "KB", "MB", "GB", "TB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };
  const fetchRecommendations = async (type, page = 1, size = 10) => {
    setLoading(true);
    try {
      let url = "";
      const params = {};

      switch (type) {
        case "personalized":
          url = "/api/torrent/recommend";
          params.limit = size;
          break;
        case "active":
          url = "/api/torrent/recommend/active";
          params.limit = size;
          break;
        case "free":
          url = "/api/torrent/recommend/free";
          params.limit = size;
          break;
        case "popular":
          url = "/api/torrent/recommend/popular";
          params.limit = size;
          break;
        case "healthy":
          url = "/api/torrent/recommend/healthy";
          params.limit = size;
          break;
        case "paged":
          url = "/api/torrent/recommend/page";
          params.page = page;
          params.size = size;
          break;
        default:
          url = "/api/torrent/recommend";
      }

      const response = await axios.get(url, {
        baseURL: "http://192.168.55.192:8080",
        headers: {Authorization: getAuthToken()},
        params,
      });

      if (response.data.code === 200) {
        // 处理分页响应
        if (type === "paged" && response.data.data) {
          setTorrents(response.data.data.records);
          setPagination({
            current: page,
            pageSize: size,
            total: response.data.data.total,
            pages: response.data.data.pages,
          });
        }
        // 处理非分页响应
        else {
          setTorrents(response.data.data || []);
          setPagination({
            current: 1,
            pageSize: size,
            total: (response.data.data || []).length,
          });
        }
      } else {
        message.error(response.data.message || "获取推荐失败");
      }
    } catch (error) {
      console.error("获取推荐失败:", error);
      message.error("获取推荐失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  const handleTabChange = (key) => {
    setActiveTab(key);
    fetchRecommendations(key, 1, pagination.pageSize);
  };
  const handlePageChange = (page, pageSize) => {
    setPagination({...pagination, current: page});
    fetchRecommendations(activeTab, page, pageSize);
  };

  useEffect(() => {
    fetchRecommendations(activeTab);
  }, []);
  return (
      <Layout className="recommend-layout">
        <Content className="recommend-content">
          <Button
              type="link"
              icon={<HomeOutlined />}
              onClick={() => navigate("/")}
              className="back-home"
          >
            返回首页
          </Button>

          <Card title="资源推荐" className="recommend-card">
            <Tabs
                activeKey={activeTab}
                onChange={handleTabChange}
                tabBarExtraContent={
                  <div className="recommend-tips">
                    <InfoCircleOutlined />
                    根据您的偏好和行为生成的个性化推荐
                  </div>
                }
            >
              <TabPane
                  key="personalized"
                  tab={
                    <span>
                  <StarOutlined /> 个性推荐
                </span>
                  }
              >
                <List
                    itemLayout="vertical"
                    dataSource={torrents}
                    loading={loading}
                    renderItem={(item) =>     <TorrentItem
                        item={item}
                        navigate={navigate}  // 传递 navigate
                    />}
                />
              </TabPane>

              <TabPane
                  key="active"
                  tab={
                    <span>
                  <FireOutlined /> 热门推荐
                </span>
                  }
              >
                <List
                    itemLayout="vertical"
                    dataSource={torrents}
                    loading={loading}
                    renderItem={(item) =>     <TorrentItem
                        item={item}
                        navigate={navigate}  // 传递 navigate
                    />}
                />
              </TabPane>

              {/* 其他推荐类型 */}
              <TabPane
                  key="free"
                  tab={
                    <span>
                  <Tag color="green">免费</Tag> 限免推荐
                </span>
                  }
              >
                <List
                    itemLayout="vertical"
                    dataSource={torrents}
                    loading={loading}
                    renderItem={(item) => <TorrentItem item={item} navigate={navigate} />}
                />
              </TabPane>
              <TabPane
                  key="healthy"
                  tab={
                    <span>
      <HeartOutlined /> 健康度推荐
    </span>
                  }
              >
                <List
                    itemLayout="vertical"
                    dataSource={torrents}
                    loading={loading}
                    renderItem={(item) => <TorrentItem item={item} navigate={navigate} />}
                />
              </TabPane>

              <TabPane
                  key="popular"
                  tab={
                    <span>
      <BarChartOutlined /> 流行推荐
    </span>
                  }
              >
                <List
                    itemLayout="vertical"
                    dataSource={torrents}
                    loading={loading}
                    renderItem={(item) => <TorrentItem item={item} navigate={navigate} />}
                />
              </TabPane>
            </Tabs>
          </Card>
        </Content>
      </Layout>
  );
};

export const RankingPage = () => {
  const [activeRankTab, setActiveRankTab] = useState("upload");
  const [leaderboardData, setLeaderboardData] = useState(mockRankings);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [uploadRes, seedingRes] = await Promise.all([
          axios.get("http://192.168.55.192:8080/api/leaderboard/upload", {
            headers: { Authorization: getAuthToken() },
          }),
          axios.get("http://192.168.55.192:8080/api/leaderboard/seeding", {
            headers: { Authorization: getAuthToken() },
          }),
        ]);

        // 处理上传排行榜数据转换
        const uploadData = uploadRes.data.code === 200
            ? uploadRes.data.data.map(item => ({
              ...item,
              scoreDisplay: formatBytes(item.score) // 将字节转换为易读格式
            }))
            : mockRankings.upload;

        // 处理保种榜数据转换
        const seedingData = seedingRes.data.code === 200
            ? seedingRes.data.data.map(item => ({
              ...item,
              scoreDisplay: `${(item.score / 3600).toFixed(1)}小时` // 秒转小时
            }))
            : mockRankings.seeding;

        setLeaderboardData({
          upload: uploadData,
          seeding: seedingData,
        });
      } catch (error) {
        console.error("排行榜加载失败，使用虚拟数据:", error);
        setLeaderboardData(mockRankings);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const getRankBadge = (index) => {
    const badges = [
      <CrownOutlined className="gold-icon" />,
      <TrophyOutlined className="silver-icon" />,
      <TrophyOutlined className="bronze-icon" />,
    ];
    return badges[index] || <span className="rank-number">{index + 1}</span>;
  };

  const renderRankList = (data) => (
      <Spin spinning={loading} tip="加载排行榜数据...">
        <List
            dataSource={data}
            renderItem={(item, index) => (
                <List.Item
                    className={`rank-item ${index < 3 ? "rank-top-" + (index + 1) : ""}`}
                    actions={[<Tag color="#722ed1">{item.scoreDisplay}</Tag>]}
                >
                  <List.Item.Meta
                      avatar={
                        <Badge className="rank-badge" count={getRankBadge(index)} />
                      }
                      title={item.username}
                      description={[<Tag>Lv.{item.userLevel}</Tag>]}
                  />
                </List.Item>
            )}
        />
      </Spin>
  );

  // 正确返回JSX结构
  return (
      <Layout className="ranking-layout">
        <Content className="ranking-content">
          <Button
              type="link"
              icon={<HomeOutlined />}
              onClick={() => navigate("/")}
              className="back-home"
          >
            返回首页
          </Button>

          <Card title="全站排行榜" className="full-ranking-card">
            <Tabs
                activeKey={activeRankTab}
                onChange={setActiveRankTab}
                animated
                tabBarGutter={32}
            >
              <TabPane
                  key="upload"
                  tab={
                    <span className="tab-title">
                  <UploadOutlined />
                  上传排行榜
                </span>
                  }
              >
                {renderRankList(leaderboardData.upload)}
              </TabPane>
              <TabPane
                  key="seeding"
                  tab={
                    <span className="tab-title">
                  <ClockCircleOutlined />
                  保种排行榜
                </span>
                  }
              >
                {renderRankList(leaderboardData.seeding)}
              </TabPane>
            </Tabs>
            <div className="ranking-footer">
              <Tag icon={<ClockCircleOutlined />} color="geekblue">
                数据每15分钟更新一次
              </Tag>
              <Tag icon={<CrownOutlined />} color="gold">
                每月最后一天23:59结算奖励
              </Tag>
            </div>
          </Card>
        </Content>
      </Layout>
  );
};

export default Home;
